package com.xd.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * @version 1.0
 * @Description 自定义线程池实现
 */
@Slf4j
@Configuration
public class TaskExecutePool {
    public final static String TaskExecutor = "TaskExecutor";

    @Autowired
    private TaskThreadPoolConfig config; // 配置属性类，见上面的代码

    //获取当前机器的核数
    public static final int cpuNum = Runtime.getRuntime().availableProcessors();

    @Bean
    public ThreadPoolTaskExecutor gatewayTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(cpuNum * 8 * 2);
        executor.setMaxPoolSize(executor.getCorePoolSize() * 2);
        executor.setQueueCapacity(500);
        executor.setKeepAliveSeconds(60);
        //executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadNamePrefix(TaskExecutor + "-");
        log.info("\n线程池配置:   cpu核心数:" + cpuNum
                + "\n核心线程数:" + executor.getCorePoolSize()
                + "\n最大线程数:" + executor.getMaxPoolSize()
                + "\n阻塞队列大小:500"
                + "\n存活时间（秒）:" + executor.getKeepAliveSeconds()
                + "\n线程前缀:" + executor.getThreadNamePrefix()
        );
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                log.info("线程池已满,执行拒绝策略,直接取消任务!");
                ((FutureTask) r).cancel(true);
                super.rejectedExecution(r, executor);
            }
        });
        return executor;
    }

    @Bean
    public ScheduledThreadPoolExecutor gatewayScheduledExecutor() {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(config.getCorePoolSize());
        executor.setMaximumPoolSize(config.getMaxPoolSize());
        executor.setKeepAliveTime(config.getKeepAliveSeconds(), TimeUnit.SECONDS);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return executor;
    }

    @Bean("delayedScheduler")
    public ScheduledExecutorService delayedScheduler() {
        return Executors.newScheduledThreadPool(1);
    }
}

